import { defineStore } from "pinia";
import { OrganizationInfoVO } from "@/entiy/vo/OrganizationInfoVO.ts";
import RequestService from "@/service/RequestService.ts";
import PromiseUtils from "@/utils/PromiseUtils.ts";
import { VxeTreePropTypes } from "vxe-pc-ui";
import ArrayUtils from "@/utils/ArrayUtils.ts";

export const useCompanyInfoManagerStore = defineStore('companyInfoManagerStore', {
    state: () => {
        return {
            // 页面是否加载中
            isPageLoading: false,

            // 树的节点配置
            treeNodeConfig: {
                isHover: true,
                isCurrent: true
            } as VxeTreePropTypes.NodeConfig,

            // 机构搜索框
            companyName: "",

            // 机构列表
            orgTreeList: [] as Array<OrganizationInfoVO>,

            // 当前选择的机构信息
            currentOrgData: {} as OrganizationInfoVO,

            // 当前选择的机构是否正在编辑
            isCurrentOrgEditing: false,
        }
    },

    getters: {},

    actions: {
        // 查询机构树结构
        async queryOrgTreeList(): Promise<void> {
            const result = await RequestService.post<Array<OrganizationInfoVO>>("/get-organization-info-list-by-name");
            if (result.isError) {
                return PromiseUtils.reject(result.errorMsg);
            }

            this.orgTreeList = result.bizDta;

            // 默认选中树中的第一条数据
            this.currentOrgData = this.orgTreeList[0];
            return PromiseUtils.resolve();
        },

        // 节点被点击时的事件
        async handleNodeClick(params: any) {
            let {node} = params;
            const data = ArrayUtils.findItemByProperty(this.orgTreeList, "orgId", node.orgId);
            if (data) {
                this.currentOrgData = data;
            }
        },

        // 更新机构信息
        async updateOrgInfo(data: OrganizationInfoVO) {
            const result = await RequestService.post<OrganizationInfoVO>("update-organization-info", data);
            if (result.isError) {
                return PromiseUtils.reject(result.errorMsg);
            }

            // 更新成功时更新数据
            const item = result.bizDta;
            if (item && item.orgId) {
                // 更新列表数据
                ArrayUtils.update(this.orgTreeList, "orgId", item.orgId, item);

                // 更新选中的当前数据
                this.currentOrgData = item;
            }
            return PromiseUtils.resolve();
        }
    }
});
